package com.coolaid.tictactoe;

import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class StringSendReceive extends Activity {
	String ip;
	int port;
	String userName;
	
	EditText chatInput;
	TextView chatWindow;
	Button sendButton;
	
	ClientSocket clientSocket;
	DataTransfer dataTransfer;
	
	boolean buttonIsClicked = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_string_send_recieve);
		
		Intent intent = getIntent();
		this.ip = intent.getStringExtra("ip");
		this.port = intent.getIntExtra("port", 4000);
		this.userName = intent.getStringExtra("userName");
		
		this.dataTransfer = new DataTransfer();
		
		clientSocket = new ClientSocket(ip, port, dataTransfer);
		clientSocket.execute(); 
		clientSocket.setTimerParent(this);
		
		this.chatInput = (EditText)findViewById(R.id.chatInput);
		this.chatWindow = (TextView)findViewById(R.id.chatWindow);
		this.chatWindow.setText("");
		this.sendButton = (Button)findViewById(R.id.sendButton);
		
		this.sendButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				buttonClicked();
			}
		});
	}
	@Override

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}

	/* This function will add the string in the input window to the chat window,
	 * and sends it to the server.
	 */
	public void buttonClicked(){
		String toSend = chatInput.getText().toString();
		this.chatWindow.append(toSend + " \n");
		dataTransfer.toSend = 1 + " "+ toSend;
		dataTransfer.mustSend = true;
		chatInput.setText("");
	}
	
	public void notifyByServer(){
		if(dataTransfer.canReceive){
			
		} else {
			Log.d("TicTacToe", "notified, string received = " + dataTransfer.received);
			String received = dataTransfer.received;
			int firstInt = Integer.parseInt(received.substring(0, 1));
			switch (firstInt) {
			case 0:
				Log.d("TicTacToe", "Login Requested");
				synchronized (dataTransfer) {
					String toSend = 3 + " " + userName;
					dataTransfer.toSend = toSend;
					dataTransfer.mustSend = true;
					Log.d("TicTacToe", "Sending: " + toSend);
				}
				Thread.currentThread().interrupt();
				break;

			default:
				break;
			}
			chatWindow.append(dataTransfer.received + " \n");
			dataTransfer.received = "";
			dataTransfer.canReceive = true;
		}
	}
}
